#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @time     : 2018/3/7 09:29
# @Author   : BYF
# file      : checkin_page.py
# @version  :

from time import sleep, strftime
from base_page import BasePage
from common import function
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select


class CheckinPage(BasePage):
    """入住页面"""
    # Action
    iframe_loc = (By.CSS_SELECTOR, "iframe#iframe1")  # iframe

    add_customer_loc = (By.CSS_SELECTOR, "div#col-op-custm a#add-cutomer")  # 添加租客按钮
    phone_loc = (By.CSS_SELECTOR, "input[data-name='phone']")  # 租客电话
    name_loc = (By.CSS_SELECTOR, "input[data-name='name']")  # 租客姓名
    idcard_loc = (By.CSS_SELECTOR, "input[data-name='idcard']")  # 证件号码
    emergency_contact_loc = (By.CSS_SELECTOR, "input[data-name='emergency_contact']")  # 紧急联系人
    emergency_phone_loc = (By.CSS_SELECTOR, "input[data-name='emergency_phone']")  # 紧急联系人电话

    sales_sources_loc = (By.CSS_SELECTOR, "select[name='sales_sources_id']")  # 销售来源
    ueto_employee_btn_loc = (By.CSS_SELECTOR, "select[name='ueto_employee_id']+div.btn-group>button")  # 选择上户按钮
    ueto_employee_list_loc = (By.CSS_SELECTOR, "select[name='ueto_employee_id']+div.btn-group>button+ul>li label")  # 上户列表
    with_employee_btn_loc = (By.CSS_SELECTOR, "select[name='with_employee_id']+div.btn-group>button")  # 选择带户按钮
    with_employee_list_loc = (By.CSS_SELECTOR, "select[name='with_employee_id']+div.btn-group>button+ul>li label")  # 上户列表

    contract_number_loc = (By.CSS_SELECTOR, "input#contract_number")  # 合同号
    begin_time_loc = (By.CSS_SELECTOR, "input[name='begin_time']")  # 合同开始时间
    contract_cyc_btn_loc = (By.CSS_SELECTOR, "div#show_year_drop>button")  # 合同结束时间
    contract_cyc_list_loc = (By.CSS_SELECTOR, "div#show_year_drop>ul a")  # 合同周期列表
    rental_loc = (By.CSS_SELECTOR, "input#rental")  # 合同租金
    deposit_loc = (By.CSS_SELECTOR, "input#deposit")  # 合同押金
    how_mortgage_loc = (By.CSS_SELECTOR, "select#how_mortgage")  # 押款方式
    how_pay_loc = (By.CSS_SELECTOR, "select#way-fu")  # 付款方式
    room_card_count_loc = (By.CSS_SELECTOR, "select[name='room_card_count']")  # 房卡数

    add_cost_loc = (By.CSS_SELECTOR, "a#add-fee")  # 添加费用按钮
    cost_name_loc = (By.CSS_SELECTOR, "div select")  # 费用科目
    cost_money_loc = (By.CSS_SELECTOR, "div input")  # 费用金额

    bill_number_loc = (By.CSS_SELECTOR, "input[name='bill_number']")  # 票据号
    is_ious_loc = (By.CSS_SELECTOR, "input[name='ious']")  # 申请月付
    store_billing_time_loc = (By.CSS_SELECTOR, "input[name='store_billing_time']")  # 记账日期
    pay_type_loc = (By.CSS_SELECTOR, "ul#pay_type a")

    # pay_typeContent_loc = (By.CSS_SELECTOR, "div#pay_typeContent>div:nth-child(1)")
    pay_money_loc = (By.CSS_SELECTOR, "div input:first-child")
    pay_explain_loc = (By.CSS_SELECTOR, "div input:last-child")

    remark_loc = (By.CSS_SELECTOR, "textarea[name='remark']")  # 合同备注

    save_btn_loc = (By.CSS_SELECTOR, "button#btn-ckin")  # 保存按钮
    cancel_btn_loc = (By.CSS_SELECTOR, "button#cancel-add")  # 取消按钮

    def _open(self, apartment_name, room_number):
        """初始化页面"""
        base_url = self.config.get("url", "base_url")
        checkin_url = self.config.get("url", "checkin_url") + str(room_number)
        self.visit(base_url)
        function.add_cookies(self.driver)
        self.visit(base_url + checkin_url)
        self.switch_to_iframe(self.iframe_loc)

    def complete_tenant_info(self, tenant_info):
        """
        完善租客信息
        :param tenant_info:租客信息，内容格式为：
        tenant_info = (
                        {
                            "phone":"15828383621",
                            "name":"Tester",
                            "idcard":"testidcard",
                            "emergency_contact":u"紧急联系人姓名,"
                            "emergency_phone":"15623121155"
                        },
                        {
                            "phone":"15828383621",
                            "name":"Tester",
                            "idcard":"testidcard",
                            "emergency_contact":u"紧急联系人姓名,"
                            "emergency_phone":"15623121155"
                        },
                        )
        :return:
        """
        i = 2

        # [self.driver.find_element(*self.add_customer_loc).click() for ii in range(1, len(tenant_info))]
        [self.locator(self.add_customer_loc).click() for ii in range(1, len(tenant_info))]

        for tenant in tenant_info:
            tenant_loc = (By.CSS_SELECTOR, "div#list-ctm>div:nth-child(%d)" % i)
            tenant_element = self.locator(tenant_loc)
            self.input_text(self.phone_loc, tenant["phone"])  # 输入电话
            sleep(1)
            self.input_text(self.name_loc, tenant["name"])  # 输入姓名
            self.input_text(self.idcard_loc, tenant["idcard"])  # 输入证件号码
            self.input_text(self.emergency_contact_loc, tenant["emergency_contact"])  # 输入紧急联系人姓名
            self.input_text(self.emergency_phone_loc, tenant["emergency_phone"])  # 输入紧急联系人电话
            i += 1

    def complete_sales_info(self, source, first_ueto_employee, with_employee, second_ueto_employee=None):
        """
        完善销售信息
        :param source:销售来源
        :param first_ueto_employee:第一个上户人
        :param with_employee: 带户人
        :param second_ueto_employee:第二个上户人
        :return:
        """
        sales_sources = Select(self.driver.find_element(*self.sales_sources_loc))  # 销售来源列表
        ueto_employees_list = self.driver.find_elements(*self.ueto_employee_list_loc)  # 上户列表
        with_employee_list = self.driver.find_elements(*self.with_employee_list_loc)  # 带户列表
        sales_sources.select_by_visible_text(source)  # 选择销售来源
        self.driver.find_element(*self.ueto_employee_btn_loc).click()  # 点击选择上户按钮
        self.check(ueto_employees_list, first_ueto_employee)  # 选择上户

        # 如果有两个上户则选择两个
        if second_ueto_employee is not None or len(second_ueto_employee) > 0:
            self.check(ueto_employees_list, second_ueto_employee)
        self.driver.find_element(*self.with_employee_btn_loc).click()  # 点击选择带户按钮
        self.check(with_employee_list, with_employee)  # 选择带户

    def complete_contract_info(self, contract_number, begin_time, contract_cycle, rental, deposit, how_mortgage,
                               how_pay, room_card_count):
        """
        完善合同信息
        :param contract_number:合同号
        :param begin_time: 合同开始时间
        :param contract_cycle: 合同周期
        :param rental:租金
        :param deposit:押金
        :param how_mortgage:押几
        :param how_pay:付几
        :param room_card_count: 房卡数
        :return:
        """
        self.send_keys(self.contract_number_loc, contract_number)  # 输入合同号
        js = "$('input[name=begin_time]').removeAttr('readonly')"  # js去掉begin_time的readonly属性
        self.driver.execute_script(js)
        self.send_keys(self.begin_time_loc, begin_time)  # 选择合同开始时间
        self.driver.find_element(*self.contract_cyc_btn_loc).click()  # 点击合同周期下拉框
        contract_cyc_list = self.driver.find_elements(*self.contract_cyc_list_loc)
        self.check(contract_cyc_list, contract_cycle)  # 选择合同周期
        self.send_keys(self.rental_loc, rental)  # 输入合同租金
        self.send_keys(self.deposit_loc, deposit)  # 输入合同押金
        mortgage_cyc = Select(self.driver.find_element(*self.how_mortgage_loc))
        mortgage_cyc.select_by_visible_text(how_mortgage)  # 选择押款方式
        pay_cyc = Select(self.driver.find_element(*self.how_pay_loc))
        pay_cyc.select_by_visible_text(how_pay)  # 选择付款方式
        room_cards = Select(self.driver.find_element(*self.room_card_count_loc))
        room_cards.select_by_visible_text(room_card_count)  # 选择房卡数

    def complete_cost_info(self, cost_info):
        """
        完善费用信息
        :param cost_info:费用数据，格式为：
        cost_info =({
                        "cost_name":"水费",
                        "cost_money":100
                    },
                    {
                        "cost_name":"电费",
                        "cost_money":100
                    },）
        :return:
        """
        i = 1
        for cost in cost_info:
            self.driver.find_element(*self.add_cost_loc).click()
            cost_loc = (By.CSS_SELECTOR, "div#fee-list>div:nth-child(%d)" % i)
            cost_element = self.driver.find_element(*cost_loc)
            cost_list = Select(cost_element.find_element(*self.cost_name_loc))
            cost_list.select_by_visible_text(cost["cost_name"])
            self.send_keys(self.cost_money_loc, cost["cost_money"], cost_element)
            i += 1

    def complete_bill_info(self, store_billing_time, pay_explain, document_number=None):
        """完善账单信息"""

        if document_number is None:
            document_number = strftime("%Y%m%d%H%M%S")

        self.send_keys(self.bill_number_loc, document_number)  # 输入票据号
        js = '$("input[name=store_billing_time]").removeAttr("readonly")'
        self.driver.execute_script(js)
        self.send_keys(self.store_billing_time_loc, store_billing_time)  # 输入记账日期

        # pay_typeContent = self.driver.find_element(*self.pay_typeContent_loc)
        # self.send_keys(self.pay_money_loc, diff_money, pay_typeContent)
        # self.send_keys(self.pay_explain_loc, pay_explain, pay_typeContent)

        pay_types = self.driver.find_elements(*self.pay_type_loc)
        for pay_type in pay_types:
            js = "return $('span#diff>span').text()"
            diff_money = self.driver.execute_script(js)
            pay_type_content = str(pay_type.get_attribute("href").split("#")[1])
            if pay_type_content == "pay2" or pay_type_content == "pay3":
                continue
            pay_type.click()
            sleep(1)
            pay_typeContent_loc = (By.CSS_SELECTOR, "div#%s>div:nth-child(1)" % pay_type_content)
            pay_typeContent = self.driver.find_element(*pay_typeContent_loc)
            if pay_type_content == "pay6":
                self.send_keys(self.pay_money_loc, diff_money, pay_typeContent)
                continue
            self.send_keys(self.pay_money_loc, diff_money, pay_typeContent)
            self.send_keys(self.pay_explain_loc, pay_explain, pay_typeContent)
            break

    # 完善备注信息
    def complete_remark(self, remark):
        self.send_keys(self.remark_loc, remark)  # 输入备注信息

    def click_save_btn(self):
        self.driver.find_element(*self.save_btn_loc).click()

    # 入住流程
    # def checkin(self):
    def checkin(self,room_number):

        # 测试数据
        apartment_name = u"周浦"
        # room_number = "4157"
        room_number = room_number
        tenant_info = (
            # {
            #     "phone": "18080885481",
            #     "name": "Tester",
            #     "idcard": "testidcard",
            #     "emergency_contact": u"紧急联系人姓名",
            #     "emergency_phone": "15623121155"
            # },
            {
                "phone": "18080885489",
                "name": "Tester",
                "idcard": "testidcard",
                "emergency_contact": u"紧急联系人姓名",
                "emergency_phone": "15623121155"
            },
            # {
            #     "phone": "15828383621",
            #     "name": "Tester",
            #     "idcard": "testidcard",
            #     "emergency_contact": u"紧急联系人姓名",
            #     "emergency_phone": "15623121155"
            # },
            # {
            #     "phone": "15828383621",
            #     "name": "Tester",
            #     "idcard": "testidcard",
            #     "emergency_contact": u"紧急联系人姓名",
            #     "emergency_phone": "15623121155"
            # },
        )

        source = u"豆瓣"
        first_ueto_employee = u"吴安维"
        second_ueto_employee = u"周进"
        # second_ueto_employee = ""
        with_employee = u"游宗学"

        contract_number = "A101"
        begin_time = "2018-01-08"
        contract_cycle = u"一年"
        rental = 4000
        deposit = 4000
        how_mortgage = u"一"
        how_pay = u"三"
        room_card_count = u"二"

        cost_info = ({
                         "cost_name": "暖气费",
                         "cost_money": 100
                     },
                     {
                         "cost_name": "服务费",
                         "cost_money": 200
                     },
                     {
                         "cost_name": "卫生费",
                         "cost_money": 300
                     }, {
                         "cost_name": "卫生费",
                         "cost_money": 300
                     })

        document_number = "xwtest" + strftime("%Y%m%d%H%M%S")
        store_billing_time = "2018-13-05"
        pay_explain = u"这个是支付备注信息~！"

        remark = u"这是测试合同时的备注信息哟~！"

        self._open(apartment_name=apartment_name, room_number=room_number)
        self.complete_tenant_info(tenant_info)
        self.complete_sales_info(source=source,
                                 first_ueto_employee=first_ueto_employee,
                                 second_ueto_employee=second_ueto_employee,
                                 with_employee=with_employee)  # 完善销售信息
        self.complete_contract_info(contract_number=contract_number,
                                    begin_time=begin_time,
                                    contract_cycle=contract_cycle,
                                    rental=rental,
                                    deposit=deposit,
                                    how_mortgage=how_mortgage,
                                    how_pay=how_pay,
                                    room_card_count=room_card_count)  # 完善合同信息
        # self.complete_cost_info(cost_info)  # 完善费用信息
        self.complete_bill_info(document_number=document_number,
                                store_billing_time=store_billing_time,
                                pay_explain=pay_explain)  # 完善账单信息
        self.complete_remark(remark=remark)  # 完善备注信息
        # self.click_save_btn()
        sleep(30)

    def test_room_list(self):
        room_list = [10102,10103,10104,10105,]

        for room_number in room_list:
            self.checkin(room_number)